package com.oracle.outsidein;

import com.oracle.outsidein.pool.OitType;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Getter
public class OutsideinManagerConfig {
    private File outsideinHome;
    private File workingDir;
    private String version = "5.8.8";
    private String platform = "linux";
    private String march = "x86-64";
    private int taskSize = 10;
    private long taskTimeout = 8000;
    private List<String> runAsArgs = new ArrayList<>();
    private Map<OitType, String> execMap;

    public OutsideinManagerConfig outsideinHome(String outsideinHome) {
        this.outsideinHome = new File(outsideinHome);
        return this;
    }

    public OutsideinManagerConfig version(String version) {
        this.version = version;
        return this;
    }

    public OutsideinManagerConfig platform(String platform) {
        this.platform = platform;
        return this;
    }

    public OutsideinManagerConfig march(String march) {
        this.march = march;
        return this;
    }

    public OutsideinManagerConfig taskSize(int taskSize) {
        this.taskSize = taskSize;
        return this;
    }

    public OutsideinManagerConfig taskTimeout(long taskTimeout) {
        this.taskTimeout = taskTimeout;
        return this;
    }

    public OutsideinManagerConfig runAsArgs(String arg) {
        this.runAsArgs.add(arg);
        return this;
    }

    public OutsideinManager build() {
        validate();
        return new OutsideinManager(this);
    }

    // 配置检查
    public void validate() {
        log.info("OutsideinManagerConfig validate...");
        if (outsideinHome == null) {
            outsideinHome = OutsideinUtils.getDefaultOfficeHome();
        }
        if (workingDir == null) {
            workingDir = new File(System.getProperty("java.io.tmpdir"));
        }
        execMap = OutsideinUtils.validateHome(outsideinHome, toolDir(null));
        OutsideinUtils.validateWorkingDirectory(workingDir);
    }

    public String toolDir(OitType oitType) {
        if (oitType == null) {
            return String.format("-%s-%s-%s/", version.replaceAll("\\.", "-"), platform, march);
        } else {
            return String.format("%s-%s-%s-%s/", oitType.toString(), version.replaceAll("\\.", "-"), platform, march);
        }
    }

    public String getCfg(OitType oitType) {
        return outsideinHome + "/" + toolDir(oitType) + "sdk/demo/default.cfg";
    }

    // wx静态资源目录 /opt/outsidein/wv-8-5-5-linux-x86-64/sdk/assets
    public File getWvAssets() {
        return new File(outsideinHome + "/" + toolDir(OitType.wv) + "sdk/assets");
    }
}
